<template>
  <div class="div1">
    <el-container>
      <el-container>
        <el-aside></el-aside>
        <el-main v-loading="loading">
          <div>
            <span v-if="config.isRoot === false || config.isRoot === 'false'">
              <el-select
                v-model="branch"
                disabled
                :placeholder="branch"
                size="medium"
                class="selector"
              >
              </el-select>
            </span>
            <!--config.isRoot为true时 -->
            <span v-if="config.isRoot === true || config.isRoot === 'true'">
              <!-- ************* -->
              <el-select
                v-model="branch"
                class="selector"
                @change="changebranch"
                filterable
                placeholder="请选择"
                size="medium"
              >
                <p>------分支({{ branchs.length }})------</p>

                <el-option
                  v-for="item in branchs"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </span>
            <div style="display: inline-block; margin-bottom: 15px">
              <el-icon class="word" @click="back"><Back /></el-icon>

              <!-- 路径 -->
              <el-breadcrumb
                :separator-icon="ArrowRight"
                style="display: inline-block; font-size: medium"
              >
                <!-- eslint-disable-next-line -->
                <el-breadcrumb-item v-for="item in $route.params">
                  <h4 v-if="item != this.$route.params.username">{{ item }}</h4>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <!--config.isRoot为true时，显示下载等按钮  -->
            <span
              v-if="config.isRoot === true || config.isRoot === 'true'"
              id="toolMenu"
            >
              <span
                v-if="userType == 1 || userType == 2"
                style="left: 24%; display: inline-block; position: relative"
              >
                <el-tooltip effect="dark" content="新建分支" placement="top">
                  <el-button icon="Plus" @click="newbranchvisible = true" />
                </el-tooltip>

                <el-tooltip effect="dark" content="删除分支" placement="top">
                  <el-button icon="Delete" @click="delBranchVisible = true" />
                </el-tooltip>

                <el-button type="warning">
                  <el-upload
                    accept=".zip"
                    :http-request="customUpload"
                    :show-file-list="false"
                    :auto-upload="true"
                    ><el-icon><upload-filled /></el-icon>
                    GitFree专用Push通道
                  </el-upload>
                </el-button>
                <!-- <el-button style="width: 40px; margin-left: 10px" @click="clone"
                  >下载</el-button
                > -->
                <el-popover placement="bottom" :width="300" trigger="click">
                  <template #reference>
                    <el-button style="margin-right: 16px">下载</el-button>
                  </template>
                  <el-menu
                    :default-active="activedownload"
                    class="el-menu-download"
                    :ellipsis="false"
                    mode="horizontal"
                    background-color="#fff"
                    text-color="black"
                    active-text-color="#ffd04b"
                    @select="handleSelectDownload"
                    style="height: 40px; margin-bottom: 10px"
                  >
                    <el-menu-item index="1">普通下载</el-menu-item>
                    <el-menu-item index="2">SSh下载</el-menu-item>
                    <el-menu-item index="3">GitFree</el-menu-item>
                  </el-menu>
                  <div v-if="activedownload == 1">
                    <div style="font-size: 17px; margin-bottom: 10px">
                      输入下载版本<el-icon><Connection /></el-icon>:
                    </div>
                    <div>请在历史版本中选择版本号</div>
                    <el-input v-model="downloadvertion" />
                    <div
                      style="text-align: center; margin-top: 5%"
                      class="inputvertion"
                      @click="vertiondownload"
                    >
                      <el-button type="goon">下载</el-button>
                    </div>
                  </div>
                  <div v-if="activedownload == 2">
                    <div style="font-size: 17px; margin-bottom: 10px">
                      SSH地址<el-icon><Paperclip /></el-icon>:
                    </div>
                    <el-input
                      v-model="sshaddress"
                      disabled
                      style="margin-bottom: 10px"
                    />
                    <div
                      style="text-align: center"
                      class="sshdownload"
                      @click="sshcopy"
                    >
                      <el-button type="goon">复制</el-button>
                    </div>
                  </div>
                  <div v-if="activedownload == 3">
                    <div
                      style="text-align: center"
                      class="clone"
                      @click="clone"
                    >
                      <div style="font-size: 17px; margin-bottom: 10px">
                        GitFree下载<el-icon><FolderChecked /></el-icon>
                      </div>
                      <el-button type="goon">下载</el-button>
                    </div>
                  </div>
                </el-popover>
              </span>
              <span v-else>
                <el-button
                  style="width: 40px; position: relative; left: 60%"
                  @click="clone"
                  >下载</el-button
                >
              </span>
            </span>
            <span v-else>
              <el-button
                @click="copycode"
                type="warning"
                style="left: 48%; position: relative"
              >
                复制
              </el-button>
            </span>
            <!--config.type为0时，显示目录  -->
            <span v-if="config.type === 0">
              <!-- eslint-disable-next-line -->
              <div v-for="data in tableData">
                <el-card
                  shadow="never"
                  class="fileName"
                  body-style="padding:10px"
                >
                  <span v-if="data.type === 0"
                    ><el-icon><Folder /></el-icon
                  ></span>
                  <span v-if="data.type === 1"
                    ><el-icon><Document /></el-icon
                  ></span>
                  <span class="word" @click="turnTo(data)">{{
                    data.indexFile
                  }}</span>
                </el-card>
              </div>
              <el-empty
                description="还没有文件哦"
                v-if="empty == true"
                :image-size="300"
              />
            </span>
          </div>

          <!-- 新建分支 -->
          <el-dialog
            v-model="newbranchvisible"
            title="新建分支"
            style="text-align: center"
          >
            <div style="text-align: center">
              <span>起点:</span>
              <el-select
                style="margin-left: 20px"
                v-model="newbranchstart"
                class="chosestart"
                placeholder="Select"
                size="large"
              >
                <el-option
                  v-for="item in branchs"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </div>
            <div style="text-align: center; margin-top: 50px">
              <span class="ml-3 w-35 text-gray-600 inline-flex items-center"
                >名称:</span
              >
              <el-input
                style="margin-left: 20px; width: 222px; height: 40px"
                v-model="newbranchname"
              />
            </div>
            <div style="text-align: center; margin-top: 30px">
              <el-button @click="newbranch" style="color: coral">
                新建分支
              </el-button>
              <el-button @click="newbranchvisible = false" style="color: coral">
                返回
              </el-button>
            </div>
          </el-dialog>

          <!-- 删除分支 -->
          <el-dialog
            v-model="delBranchVisible"
            title="删除分支"
            style="text-align: center"
          >
            <div style="text-align: center">
              选择要删除的分支:
              <el-select
                style="margin-left: 20px"
                v-model="delBranchName"
                class="chosestart"
                placeholder="Select"
                size="large"
              >
                <el-option
                  v-for="item in branchs"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </div>

            <div style="text-align: center; margin-top: 30px">
              <el-button @click="delBranch" style="color: coral">
                删除分支
              </el-button>
              <el-button @click="delBranchVisible = false" style="color: coral">
                返回
              </el-button>
            </div>
          </el-dialog>

          <el-dialog
            v-model="checkcodevisible"
            title="GitFree专用Push通道"
            style="text-align: center"
          >
            <div
              v-if="checkcodestate == 1"
              class="checkcode1"
              style="width: 100%"
            >
              <h2 style="margin-bottom: 20px">Step 2 确认更改文件</h2>
              <div class="message">一旦确认无法更改</div>
              <div
                class="shownotcommit"
                style="
                  display: flex;
                  justify-content: flex-start;
                  margin-bottom: 20px;
                  border-bottom: 1px solid black;
                  height: 200px;
                "
              >
                <span
                  class="Untracked"
                  style="
                    text-align: center;
                    width: 25%;
                    margin-top: 0px;
                    height: 150px;
                  "
                >
                  <div style="margin-bottom: 20px; font-size: 18px">
                    Untracked
                  </div>
                  <el-scrollbar>
                    <div style="height: 150px">
                      <!-- eslint-disable-next-line -->
                      <div
                        v-for="Untrack in Untracked"
                        style="margin-left: 10px; margin-right: 10px"
                      >
                        <el-card
                          class="elshowcard"
                          shadow="hover"
                          @click="addready(Untrack)"
                          >{{ Untrack }}</el-card
                        >
                      </div>
                    </div>
                  </el-scrollbar>
                </span>
                <span
                  class="Modified"
                  style="
                    text-align: center;
                    margin-top: 0px;
                    width: 25%;
                    height: 150px;
                  "
                >
                  <div style="margin-bottom: 20px; font-size: 18px">
                    Modified
                  </div>
                  <el-scrollbar>
                    <div style="height: 120px">
                      <!-- eslint-disable-next-line -->
                      <div
                        v-for="Modifie in Modified"
                        style="margin-left: 10px; margin-right: 10px"
                      >
                        <el-card
                          class="elshowcard"
                          shadow="hover"
                          @click="addready(Modifie)"
                          >{{ Modifie }}</el-card
                        >
                      </div>
                    </div>
                  </el-scrollbar>
                </span>
                <span
                  class="Missing"
                  style="
                    text-align: center;
                    margin-top: 0px;
                    height: 150px;
                    width: 25%;
                  "
                >
                  <div style="margin-bottom: 20px; font-size: 18px">
                    Missing
                  </div>
                  <el-scrollbar>
                    <div style="height: 120px">
                      <!-- eslint-disable-next-line -->
                      <div
                        v-for="Miss in Missing"
                        style="margin-left: 10px; margin-right: 10px"
                      >
                        <el-card
                          class="elshowcard"
                          shadow="hover"
                          @click="rmready(Miss)"
                          >{{ Miss }}</el-card
                        >
                      </div>
                    </div>
                  </el-scrollbar>
                </span>
                <span
                  class="Conflicting"
                  style="
                    text-align: center;
                    margin-top: 0px;
                    height: 150px;
                    width: 25%;
                  "
                >
                  <div style="margin-bottom: 20px; font-size: 18px">
                    Conflicting
                  </div>
                  <el-scrollbar>
                    <div style="height: 120px">
                      <!-- eslint-disable-next-line -->
                      <div
                        v-for="Conflict in Conflicting"
                        style="margin-left: 10px; margin-right: 10px"
                      >
                        <el-card
                          class="elshowcard"
                          shadow="hover"
                          @click="addready(Conflict)"
                          >{{ Conflict }}</el-card
                        >
                      </div>
                    </div>
                  </el-scrollbar>
                </span>
              </div>
              <div
                class="showalltocommit"
                style="
                  display: flex;
                  justify-content: flex-start;
                  margin-top: 50px;
                  height: 200px;
                "
              >
                <span
                  class="Added"
                  style="
                    text-align: center;
                    width: 33%;
                    margin-top: 0px;
                    height: 150px;
                  "
                >
                  <div style="margin-bottom: 20px; font-size: 18px">Added</div>
                  <el-scrollbar>
                    <div style="height: 120px">
                      <!-- eslint-disable-next-line -->
                      <div
                        v-for="Add in Added"
                        style="margin-left: 10px; margin-right: 10px"
                      >
                        <div style="height: 40px">{{ Add }}</div>
                      </div>
                    </div>
                  </el-scrollbar>
                </span>
                <span
                  class="Changed"
                  style="
                    text-align: center;
                    margin-top: 0px;
                    width: 34%;
                    height: 150px;
                  "
                >
                  <div style="margin-bottom: 20px; font-size: 18px">
                    Changed
                  </div>
                  <el-scrollbar>
                    <div style="height: 120px">
                      <!-- eslint-disable-next-line -->
                      <div
                        v-for="Change in Changed"
                        style="margin-left: 10px; margin-right: 10px"
                      >
                        <div style="height: 40px">{{ Change }}</div>
                      </div>
                    </div>
                  </el-scrollbar>
                </span>
                <span
                  class="Removed"
                  style="
                    text-align: center;
                    height: 150px;
                    margin-top: 0px;
                    width: 33%;
                  "
                >
                  <div style="margin-bottom: 20px; font-size: 18px">
                    Removed
                  </div>
                  <el-scrollbar>
                    <div style="height: 120px">
                      <!-- eslint-disable-next-line -->
                      <div
                        v-for="Remove in Removed"
                        style="margin-left: 10px; margin-right: 10px"
                      >
                        <div style="height: 40px">{{ Remove }}</div>
                      </div>
                    </div>
                  </el-scrollbar>
                </span>
              </div>
              <div class="whattoadd">
                <div
                  style="
                    margin-top: 10px;
                    width: 500px;
                    height: 20px;
                    font-size: 20px;
                  "
                >
                  选择文件Add:
                </div>
                <div
                  style="margin-top: 10px; min-height: 50px; margin-left: 20px"
                >
                  <!-- eslint-disable-next-line -->
                  <span
                    v-for="ready in ReadyToAdd"
                    style="
                      display: inline-block;
                      font-size: 17px;
                      margin-right: 15px;
                    "
                    >{{ ready }}</span
                  >
                  <!-- eslint-disable-next-line -->
                  <span
                    v-for="rm in ReadyToRm"
                    style="
                      display: inline-block;
                      margin-right: 15px;
                      font-size: 17px;
                    "
                    >{{ rm }}</span
                  >
                </div>
              </div>
              <div
                class="gittoadd"
                style="display: flex; justify-content: center"
              >
                <el-button @click="addall" size="large">ChooseAll</el-button>
                <el-button @click="gitaddrm" size="large">Add</el-button>
                <el-button @click="gittocommit" size="large" type="warning"
                  >Commit</el-button
                >
                <el-button @click="toDetail" size="large">Detail</el-button>
                <el-dialog
                  class="DetailDialog"
                  v-model="Detailvisible"
                  title="Detail"
                >
                  <div v-highlight>
                    <code
                      id="codeblock"
                      class="language-javascript hljs"
                      style=""
                    >
                      {{ DetailCode }}</code
                    >
                  </div>
                </el-dialog>
              </div>
              <!--选择分支-->
            </div>
            <div v-if="checkcodestate == 0" class="checkcode0">
              <h2 style="margin-bottom: 20px">Step 1 选择分支</h2>
              <div class="message">
                <div style="margin-bottom: 6px">
                  您的目标仓库地址为{{ url }},请您务必确认;
                </div>
                <div>
                  为确保上传成功，请您选择与您本地修改分支同名的远程分支：
                </div>
              </div>
              <div>
                <!-- eslint-disable-next-line -->
                <div v-for="bran in uploadbranchs">
                  <el-popconfirm
                    title="确定选择该分支?"
                    confirm-button-text="是"
                    cancel-button-text="否"
                    @confirm="chosebranch(bran)"
                  >
                    <template #reference>
                      <el-card class="branchcard" shadow="hover">
                        {{ bran }}</el-card
                      >
                    </template>
                  </el-popconfirm>
                </div>
              </div>
            </div>
            <div v-if="checkcodestate == 2">
              <h2 style="margin-bottom: 20px">Step 3 提交信息</h2>
              <div class="message">
                建议您填写详细的提交内容, 它将作为您提交历史的显示
              </div>
              <div>
                <div
                  style="font-size: 20px; text-align: left; margin-bottom: 20px"
                >
                  请输入提交信息
                </div>
                <div style="margin-bottom: 20px">
                  <el-input v-model="commitmessage"></el-input>
                </div>
                <div style="text-align: center">
                  <el-button @click="gitcommit" size="large">提交</el-button>
                </div>
              </div>
            </div>
            <div v-if="checkcodestate == 30">
              <h2 style="margin-bottom: 20px">Step 4 确认信息</h2>
              <div class="message">请确认您提交的信息与远程分支的差异</div>
              <div>
                <div v-highlight>
                  <code
                    id="codeblock"
                    class="language-javascript hljs"
                    style=""
                  >
                    {{ DiffCode }}</code
                  >
                </div>
              </div>
              <div style="text-align: center">
                <el-button type="warning" size="large" @click="gitpush"
                  >推送</el-button
                >
              </div>
            </div>
            <div v-if="checkcodestate == 31" style="text-align: center">
              <div style="font-size: 40px; text-align: center">推送成功</div>
              <div>
                <el-icon size="200px"><Sunrise /></el-icon>
              </div>
              <div>
                <el-button round size="large" @click="getend"> 确定 </el-button>
              </div>
            </div>
            <div v-if="checkcodestate == 32">
              <div style="height: 100px; font-size: 40px; text-align: center">
                合并冲突
              </div>
              <div style="margin-bottom: 30px">
                <!-- eslint-disable-next-line -->
                <div v-for="key in conflictinfokeys" style="font-size: 17px">
                  <el-card>{{ key + ":" + conflictinfo.get(key) }}</el-card>
                </div>
              </div>
              <div
                style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
              >
                <el-button round size="large" @click="getend"> 确定 </el-button>
                <el-button round size="large" @click="downloadconflict">
                  下载
                </el-button>
              </div>
            </div>
          </el-dialog>
          <!--config.type为1,显示代码  -->
          <span v-if="config.type === 1">
            <div style="margin-top: 2%">
              <div v-highlight>
                <pre>
                  <code id="codeblock" :language="codeLang" class="hljs"  >{{code}}</code>
                </pre>
              </div>
            </div>
          </span>
          <span v-else>
            <!--config.isRoot为true时，打开README.md  -->
            <div
              v-if="
                (config.isRoot === true || config.isRoot === 'true') &&
                tableData != null
              "
              class="div2"
            >
              <h3>README.md</h3>
              <v-md-editor
                v-model="text"
                mode="edit"
                default-show-toc="true"
                left-toolbar=""
              ></v-md-editor>
            </div>
            <el-divider />
          </span>
        </el-main>

        <!-- 底部 -->
        <el-footer> </el-footer>
      </el-container>
      <!-- <button @click="test">test</button> -->
      <span v-if="config.isRoot === true || config.type === 0">
        <!-- 右边栏 -->
        <el-aside width="400px">
          <div style="margin-top: 30px">
            <div style="margin-left: 40px">
              <h4>仓库简介</h4>
              <textarea
                rows="6"
                cols="30"
                v-model="intro"
                readonly
                style="
                  font-family: '微软雅黑';
                  resize: none;
                  border: none;
                  outline: none;
                  font-size: 16px;
                  line-height: 1.7;
                  text-indent: 30px;
                "
              ></textarea>
            </div>
            <div style="left: -50px">
              <HistoryRecord ref="child" />
            </div>
          </div>
        </el-aside>
      </span>
    </el-container>
  </div>
</template>

<script>
import Prism from "prismjs";
import { ElMessage } from "element-plus";
import * as monaco from "monaco-editor";
import request from "@/utils/request";
import HistoryRecord from "../HistoryRecord.vue";
import axios from "axios";
export default {
  name: "HouseCode",
  components: {
    HistoryRecord,
  },
  data() {
    return {
      downloadvertion: "",
      sshaddress: "sshaddress",
      activedownload: "1",
      DiffCode: "",
      DetailCode: "",
      Detailvisible: false,
      url: "",
      empty: false, //是否有目录
      loading: true,
      delBranchVisible: false,
      delBranchName: "",
      conflictinfokeys: [],
      conflictinfo: {},
      uploadbranch: "",
      uploadbranchs: ["first", "second"],
      commitmessage: "",
      filename: "",
      checkcodestate: 0,
      checkcodevisible: false,
      ReadyToAdd: [],
      ReadyToRm: [],
      Added: [],
      Changed: [],
      Removed: [],
      Modified: [],
      Missing: [],
      Untracked: [],
      Conflicting: [],

      newbranchvisible: false,
      newbranchstart: "",
      newbranchname: "",
      userType: 1,
      branchs: ["master"],
      branch: "master",
      tableData: [],
      code: "return",
      text: ``,
      intro: "",
      config: {
        isRoot: true, //是否是根路径
        type: 0, //为0表示为目录，1为文件
      },
      codeLang: "javascript",
    };
  },
  mounted() {
    this.getsshaddress();
    if (this.$route.params.index != null) {
      this.$router.push(
        "/househomepage/" +
          this.$route.params.username +
          "/" +
          this.$route.params.housename +
          "/housecode"
      );
    }
    //变更到master分支
    request
      .get(
        `/branch/changeBranch?username=${this.$route.params.username}&housename=${this.$route.params.housename}&changebranchname=master`
      )
      .then((res) => {
        console.log(res);
      });
    //获取所有分支
    this.getAllBranch();
    //获取初始目录
    request
      .get(
        `house/init?ownnername=${this.$route.params.username}&housename=${this.$route.params.housename}`
      )
      .then((res) => {
        console.log(res);
        this.tableData = res.data.data;
        if (this.tableData == null) {
          this.empty = true;
        }
        this.intro = res.message;
      });

    //获取用户的类型
    request
      .post(
        `/house/getusertype?ownername=${this.$route.params.username}&housename=${this.$route.params.housename}`
      )
      .then((res) => {
        this.userType = res.data;
        window.sessionStorage.setItem("userType", res.data);
        console.log(res);
      });
    this.initMD();
    this.loading = false;
  },
  created() {
    this.updateViewBranch();
  },
  methods: {
    getsshaddress() {
      request
        .get(
          "/house/getcloneurl?ownername=" +
            this.$route.params.username +
            "&housename=" +
            this.$route.params.housename
        )
        .then((res) => {
          if (res.code == 200) {
            this.sshaddress = res.message;
          } else {
            ElMessage({
              message: res.message,
              type: "error",
            });
          }
        });
    },
    vertiondownload() {
      request({
        url:
          "/versiondownload?housename=" +
          this.$route.params.housename +
          "&username=" +
          sessionStorage.getItem("username") +
          "&version=" +
          this.downloadvertion,
        responseType: "blob",
        method: "post",
      }).then((res) => {
        const blob = new Blob([res], {
          type: "application/zip,charset=UTF-8",
        });
        var a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = `${this.$route.params.housename}.zip`;
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        a.remove();
        console.log("下载成功");
        this.downloadvertion = "";
      });
    },
    handleSelectDownload(index) {
      this.activedownload = index;
    },
    toDiff() {
      request({
        url:
          "/status/diff?housename=" +
          this.$route.params.housename +
          "&detail=git diff " +
          this.branch +
          " " +
          "origin/" +
          this.branch,
        responseType: "blob",
        method: "get",
      }).then((res) => {
        let blob = new Blob([res], { type: "application/json" }); // res就是接口返回的文件流了
        var reader = new FileReader();
        reader.readAsText(blob, "utf-8");
        let self = this; //onload this指向为window中转一下
        reader.onload = function () {
          self.DiffCode = reader.result;
          self.DiffCode = self.DetailCode.replace(/\r\n/g, "<br/>");
          console.log("resssssssssssssssssssssult为:" + reader.result);
        };
      });
    },
    toDetail() {
      request({
        url:
          "/status/diff?housename=" +
          this.$route.params.housename +
          "&detail=git diff " +
          this.branch +
          " " +
          "origin/" +
          this.branch,
        responseType: "blob",
        method: "get",
      }).then((res) => {
        let blob = new Blob([res], { type: "application/json" }); // res就是接口返回的文件流了
        var reader = new FileReader();
        reader.readAsText(blob, "utf-8");
        let self = this; //onload this指向为window中转一下
        reader.onload = function () {
          self.DetailCode = reader.result;
          self.DetailCode = self.DetailCode.replace(/\r\n/g, "<br/>");
          console.log("resssssssssssssssssssssult为:" + reader.result);
        };
        this.Detailvisible = true;
      });
    },
    delBranch() {
      request
        .get(
          `/branch/deleteBranch?username=${this.$route.params.username}&housename=${this.$route.params.housename}&deletebranchname=${this.delBranchName}`
        )
        .then((res) => {
          if (res.code == 200) {
            ElMessage("成功删除分支:" + this.delBranchName);
            this.getAllBranch();
          } else {
            ElMessage(res.message);
          }
        })
        .catch((error) => {
          ElMessage({ message: res.message, type: "error" });
        });
      this.delBranchVisible = false;
    },
    updateViewBranch() {
      request
        .get(
          "/house/updateView?ownnername=" +
            this.$route.params.username +
            "&housename=" +
            this.$route.params.housename
        )
        .then((res) => {
          if (res.code == 200) {
            console.log("成功更新view");
          } else {
            console.log("失败更新view");
          }
        })
        .catch((error) => {
          console.log("失败更新view=error");
        });
    },
    getuploadbranch() {
      request
        .get("/status/getRepBranch?filename=" + this.filename)
        .then((res) => {
          if (res.code == 200) {
            this.uploadbranchs = res.data.branch;
            this.url = res.data.url;
            this.checkcodestate = 0;
            this.checkcodevisible = true;
          }
        })
        .catch((error) => {
          this.uploadbranchs = ["1", "2", "3"];
        });
    },
    chosebranch(branch) {
      console.log(branch);
      request
        .get(
          "/status/setRepBranch?filename=" + this.filename + "&branch=" + branch
        )
        .then((res) => {
          this.uploadbranch = branch;
          this.getallstatus();
          setTimeout(() => {
            if (this.Conflicting.length != 0)
              ElMessage({
                showClose: true,
                message: "文件有必须解决的冲突!",
                type: "error",
              });
          }, 1000);
          this.checkcodestate = 1;
        });
    },
    gitaddrm() {
      this.gitadd();
      this.gitrm();
    },
    gitrm() {
      console.log(this.ReadyToRm);
      request
        .post(
          "/status/setrm?filename=" +
            this.filename +
            "&id=" +
            this.$route.params.username,
          this.ReadyToRm
        )
        .then((res) => {
          if (res.code == 200) {
            console.log("添加暂存区" + this.ReadyToRm);
            console.log("添加到暂存区成功");
            this.ReadyToRm = [];
            this.getallstatus();
          } else {
            console.log("添加到暂存区出错");
          }
        })
        .catch((error) => {
          console.log("添加到暂存区出错");
        });
    },
    gitadd() {
      console.log(this.ReadyToAdd);
      request
        .post(
          "/status/setadd?filename=" +
            this.filename +
            "&id=" +
            this.$route.params.username,
          this.ReadyToAdd
        )
        .then((res) => {
          if (res.code == 200) {
            console.log("添加暂存区" + this.ReadyToAdd);
            console.log("添加到暂存区成功");
            this.ReadyToAdd = [];
            this.getallstatus();
          } else {
            console.log("添加到暂存区出错");
          }
        })
        .catch((error) => {
          console.log("添加到暂存区出错");
        });
    },
    getallstatus() {
      request
        .get(
          "/status/getAllStatus?filename=" +
            this.filename +
            "&id=" +
            this.$route.params.username
        )
        .then((res) => {
          if (res.code == 200) {
            this.Changed = res.data.changed;
            this.Added = res.data.added;
            this.Removed = res.data.removed;
            this.Untracked = res.data.untracked;
            this.Modified = res.data.modified;
            this.Missing = res.data.missing;
            this.Conflicting = res.data.conflicting;
            if (this.Conflicting.length != 0)
              ElMessage({
                showClose: true,
                message: "文件有必须解决的冲突!",
                type: "error",
              });
            console.log("所有信息" + res.data);
          } else {
            console.log("获取git信息失败");
          }
        });
    },
    gittocommit() {
      this.checkcodestate = 2;
    },
    gitcommit() {
      request
        .get(
          "/status/commit?filename=" +
            this.filename +
            "&content=" +
            this.commitmessage +
            "&remoteBranch=" +
            this.uploadbranch +
            "&remote="
        )
        .then((res) => {
          if (res.code == 200) {
            this.toDiff();
            this.checkcodestate = 30;
          } else {
            this.checkcodestate = 32;
            this.conflictinfo = new Map(Object.entries(res.data));
            this.conflictinfokeys = this.conflictinfo.keys();
            ElMessage({
              showClose: true,
              message: res.message,
              type: "error",
            });
          }
        })
        .catch((error) => {
          alert("响应错误");
        });
    },
    gitpush() {
      request
        .get(
          "/status/push?housename=" +
            this.$route.params.housename +
            "&remotebranch=" +
            this.uploadbranch +
            "&remote="
        )
        .then((res) => {
          if (res.code == 200) {
            this.updateViewBranch();
            //变更到master分支
            request
              .get(
                `/branch/changeBranch?username=${this.$route.params.username}&housename=${this.$route.params.housename}&changebranchname=master`
              )
              .then((res) => {
                console.log(res);
              });
            //获取所有分支
            this.getAllBranch();
            //获取初始目录
            request
              .get(
                `house/init?ownnername=${this.$route.params.username}&housename=${this.$route.params.housename}`
              )
              .then((res) => {
                console.log(res);
                this.tableData = res.data.data;
                if (this.tableData == null) {
                  this.empty = true;
                }
                this.intro = res.message;
              });
            this.initMD();
            this.loading = false;
            this.$refs.child.getActivities();
            this.checkcodestate = 31;
          } else {
            ElMessage({
              showClose: true,
              message: "发生异常,请尝试重新上传",
              type: "error",
            });
          }
        })
        .catch((error) => {
          ElMessage({
            showClose: true,
            message: "发生异常,请尝试重新上传",
            type: "error",
          });
        });
    },
    getend() {
      this.checkcodestate = 0;
      this.checkcodevisible = false;
      this.uploadbranch = "";
      this.uploadbranchs = [];
      this.commitmessage = "";
      this.filename = "";
      this.ReadyToAdd = [];
      this.ReadyToRm = [];
      this.Added = [];
      this.Changed = [];
      this.Removed = [];
      this.Modified = [];
      this.Missing = [];
      this.Untracked = [];
      this.conflictinfo = [];
      this.conflictinfokeys = [];
    },
    addall() {
      for (let i in this.Untracked) this.addready(this.Untracked[i]);
      for (let i in this.Conflicting) this.addready(this.Conflicting[i]);
      for (let i in this.Modified) this.addready(this.Modified[i]);
      for (let i in this.Missing) this.rmready(this.Missing[i]);
    },
    addready(UntrackedFile) {
      for (let i in this.ReadyToAdd) {
        if (this.ReadyToAdd[i] == UntrackedFile) return;
      }
      console.log("addready:" + UntrackedFile);
      this.ReadyToAdd.push(UntrackedFile);
    },
    rmready(UntrackedFile) {
      for (let i in this.ReadyToRm) {
        if (this.ReadyToRm[i] == UntrackedFile) return;
      }
      console.log("rmready:" + UntrackedFile);
      this.ReadyToRm.push(UntrackedFile);
    },
    //执行git add xxx

    //上传文件
    customUpload(file) {
      let FormDatas = new FormData();
      FormDatas.append("file", file.file);
      this.filename = file.file.name;
      console.log(this.filename);
      request
        .post(
          "http://localhost:8090/upload?userid=" +
            sessionStorage.getItem("userid"),
          FormDatas,
          {
            "Content-Type": "multipart/form-data;",
          }
        )
        .then((res) => {
          if (res.code == 200) {
            alert(res.message);
            setTimeout(this.getuploadbranch(), 3000);
          } else {
            alert(res.message);
          }
        });
    },
    //切换分支
    changebranch() {
      request
        .get(
          `/branch/changeBranch?username=${this.$route.params.username}&housename=${this.$route.params.housename}&changebranchname=${this.branch}`
        )
        .then((res) => {
          console.log(res);
          //获取初始目录
          request
            .get(
              `house/init?ownnername=${this.$route.params.username}&housename=${this.$route.params.housename}`
            )
            .then((res) => {
              console.log(res);
              this.tableData = res.data.data;
              this.intro = res.message;
            });
        });
    },
    sshcopy() {
      var input = document.createElement("input"); // 创建input标签，只有input标签选中可以
      input.setAttribute("id", "copyInput"); // 给input一个id属性
      input.setAttribute("value", this.sshaddress); // 给input一个value属性，属性值是变量span的文本
      document.getElementsByTagName("body")[0].appendChild(input); // body里面添加input实体
      document.getElementById("copyInput").select(); // 使用js去通过id找到并执行input实体的全部选中
      document.execCommand("Copy"); //原生copy方法执行浏览器复制命令
      document.getElementById("copyInput").remove(); // 为避免下次页面添加copy方法 所以这里copy完之后要移除input实体
    },
    //复制代码
    copycode() {
      // 其实逻辑是执行了把复制目标赋值给创建的input的value，使用选中value执行复制 复制完然后移除input的原理
      var Url2 = this.code;
      console.log(Url2);
      var input = document.createElement("input"); // 创建input标签，只有input标签选中可以
      input.setAttribute("id", "copyInput"); // 给input一个id属性
      input.setAttribute("value", Url2); // 给input一个value属性，属性值是变量span的文本
      document.getElementsByTagName("body")[0].appendChild(input); // body里面添加input实体
      document.getElementById("copyInput").select(); // 使用js去通过id找到并执行input实体的全部选中
      document.execCommand("Copy"); //原生copy方法执行浏览器复制命令
      document.getElementById("copyInput").remove(); // 为避免下次页面添加copy方法 所以这里copy完之后要移除input实体
    },
    getAllBranch() {
      request
        .get(
          `/branch/getAllBranch?username=${this.$route.params.username}&housename=${this.$route.params.housename}`
        )
        .then((res) => {
          if (res.code == 200) {
            console.log(res);
            this.branchs = res.data;
          }
        });
    },
    //新建分支
    newbranch() {
      request
        .get(
          `/branch/createBranch?username=${this.$route.params.username}&housename=${this.$route.params.housename}&createbranchname=${this.newbranchname}&sourcebranchname=${this.newbranchstart}`
        )
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            ElMessage({
              showClose: true,
              message: res.message,
              type: "success",
            });
            this.getAllBranch();
            //获取所有分支
          } else {
            ElMessage({
              showClose: true,
              message: res.message,
              type: "error",
            });
          }
          this.getAllBranch();
        })
        .catch((error) => {
          ElMessage({
            showClose: true,
            message: res.message,
            type: "error",
          });
          this.getAllBranch();
        });
    },
    turnTo(e) {
      var paths = this.$route.path.split("/");
      var temp = "";
      for (var i = 5; i < paths.length; ++i) {
        temp += "/" + paths[i];
      }
      temp += "/" + e.indexFile;
      console.log("temp:" + temp);
      if (e.type == 0) {
        request
          .post(
            `openfolder?ownnername=${this.$route.params.username}&housename=${this.$route.params.housename}&filename=${temp}`
          )
          .then((res) => {
            console.log(res);
            this.tableData = res.data;
            this.isRoot = false;
          });
      }
      //更新
      this.config.isRoot = false;
      this.config.type = e.type;
      if (e.type == 1) {
        this.setCodeLang(e.indexFile);
        this.initEditor(temp);
      }
      this.$router.push(this.$route.path + "/" + e.indexFile);
    },
    back() {
      if (this.$route.params.index != null) {
        var paths = this.$route.path.split("/");
        var temp = "";
        for (var i = 5; i < paths.length; ++i) {
          temp += "/" + paths[i];
        }
        console.log("temp:" + temp);
        request
          .post(
            `back?ownnername=${this.$route.params.username}&housename=${this.$route.params.housename}&filename=${temp}`
          )
          .then((res) => {
            this.tableData = res.data;
            this.config.type = 0;
            this.config.isRoot = res.message;

            this.$router.back(-1);
            console.log(this.config.isRoot);
          });
      }
    },
    clone() {
      request({
        url: `/download?username=${this.$route.params.username}&housename=${this.$route.params.housename}`,
        responseType: "blob", //一定要记得加这行，设置服务器响应的数据类型为blob类型
        method: "post", //当前请求的请求方式
      }).then((res) => {
        const blob = new Blob([res], { type: "application/zip,charset=UTF-8" });
        var a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = `${this.$route.params.housename}.zip`;
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        a.remove();
      });
    },
    downloadconflict() {
      request({
        url:
          "/status/download?id=" +
          sessionStorage.getItem("userid") +
          "&filename=" +
          this.filename,
        responseType: "blob", //一定要记得加这行，设置服务器响应的数据类型为blob类型
        method: "post", //当前请求的请求方式
      }).then((res) => {
        const blob = new Blob([res], {
          type: "application/zip,charset=UTF-8",
        });
        var a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = `${this.$route.params.housename}.zip`;
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        a.remove();
        console.log("下载成功");
      });
    },
    initEditor(e) {
      request({
        url: `/openfile?ownnername=${this.$route.params.username}&housename=${this.$route.params.housename}&filename=${e}`,
        responseType: "blob", //一定要记得加这行，设置服务器响应的数据类型为blob类型
        method: "get", //当前请求的请求方式
      }).then((res) => {
        let blob = new Blob([res], { type: "application/json" }); // res就是接口返回的文件流了
        var reader = new FileReader();
        reader.readAsText(blob, "utf-8");
        let self = this; //onload this指向为window中转一下
        reader.onload = function (e) {
          console.log(reader.result);
          self.code = reader.result;
        };
      });
    },
    setCodeLang(e) {
      var type = e.split(".")[1];
      console.log(type);
      if (type != null && type != "") {
        if (type == "cpp") this.codeLang = "cpp";
        else if (type == "java") this.codeLang = "java";
        else if (type == "js") this.codeLang = "javascript";
      }
    },
    initMD() {
      request({
        url: `/openfile?ownnername=${this.$route.params.username}&housename=${this.$route.params.housename}&filename=/README.md`,
        responseType: "blob", //一定要记得加这行，设置服务器响应的数据类型为blob类型
        method: "get", //当前请求的请求方式
      }).then((res) => {
        let blob = new Blob([res], { type: "application/json" }); // res就是接口返回的文件流了
        var reader = new FileReader();
        reader.readAsText(blob, "utf-8");
        let self = this; //onload this指向为window中转一下
        reader.onload = function (e) {
          console.log(reader.result);
          self.text = reader.result;
        };
      });
    },
  },
};
</script>

<style scoped>
* {
  margin: 0;
}
.elshowcard /deep/ .el-card__body {
  margin-top: 5px;
  padding: 0;
  cursor: pointer;
  height: 30px;
}
.elshowcard:hover {
  color: cornflowerblue;
}
.branchcard {
}
.branchcard:hover {
  color: cornflowerblue;
}
.div1 {
  position: absolute;
  left: 20%;
  width: 1200px;
}
.selector {
  width: 100px;
}
.myhref {
  margin-left: 10px;
  text-decoration: none;
  color: #000;
}
.div2 {
  width: 100%;
  margin-bottom: 2%;
  margin-top: 10%;
}
#editor {
  width: 1000px;
  height: 100%;
  text-align: left;
}
.word {
  margin-left: 10px;
  color: #000;
}
.word:hover {
  cursor: Pointer;
}
textarea:hover {
  cursor: default;
}
.fileName {
  height: 40px;
}
#bread {
  cursor: Pointer;
}

/* new */
pre {
  position: relative;
  min-width: 600px;
  margin: 0;
}
.hljs {
  display: block;
  width: 80%;
  margin: 0;
  padding: 1px;
  color: #000000;
  font-weight: 400;
  font-size: 1rem;
  font-family: "微软雅黑";
  line-height: 1.5;
  white-space: pre-wrap;
  border: 0;
}
.hljs ol {
  margin: 0 0 0 35px;
  padding: 0;
  list-style-type: decimal;
}
.hljs ol li {
  /* padding: 5px;
   padding-left: 10px; */
  color: #abb2bf;
  white-space: pre;
  /* list-style: decimal-leading-zero; */
  list-style-position: outside;
  border-left: 1px solid #c5c5c5;
}
.message {
  -webkit-text-size-adjust: 100%;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial,
    "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Liberation Sans",
    "PingFang SC", "Microsoft YaHei", "Hiragino Sans GB", "Wenquanyi Micro Hei",
    "WenQuanYi Zen Hei", "ST Heiti", SimHei, SimSun, "WenQuanYi Zen Hei Sharp",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  text-align: left;
  box-sizing: inherit;
  position: relative;
  min-height: 1em;
  margin: 1em 0em;
  padding: 1em 1.5em;
  line-height: 1.4285em;
  transition: opacity 0.1s ease, color 0.1s ease, background 0.1s ease,
    box-shadow 0.1s ease, -webkit-box-shadow 0.1s ease;
  font-size: 1em;
  border-radius: 4px;
  border: 1px solid #e3e9ed;
  background: #fff;
  margin-bottom: 10px;
  background-color: #ffe8e6;
  color: #db2828;
  box-shadow: 0px 0px 0px 1px #db2828 inset, 0px 0px 0px 0px rgba(0, 0, 0, 0);
  margin-top: 0px;
}
.el-button--goon {
  color: #fff;
  background-color: #f09409;
  border-color: #f09409;
  height: 34px;
  width: 80px;
  line-height: 34px;
  padding: 10 20px;
}
</style>
